package com.yungu.swift.system.sys.service.impl;

import com.alibaba.dubbo.config.annotation.Service;
import com.yungu.swift.base.ResponseData;
import com.yungu.swift.base.mapper.IMapper;
import com.yungu.swift.base.service.impl.BaseServiceImpl;
import com.yungu.swift.system.sys.dao.SysRoleResourceMapper;
import com.yungu.swift.system.sys.model.dto.SysRoleResourceDto;
import com.yungu.swift.system.sys.model.param.AdminRoleResourceAddParam;
import com.yungu.swift.system.sys.service.SysRoleResourceService;
import com.yungu.swift.utils.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;


/**
 * SysRoleResourceServiceImpl
 **/
@Service
public class SysRoleResourceServiceImpl extends BaseServiceImpl<SysRoleResourceDto> implements SysRoleResourceService {

    @Autowired
    private SysRoleResourceMapper sysRoleResourceMapper;

    @Override
    protected IMapper<SysRoleResourceDto> getMapper() {
        return sysRoleResourceMapper;
    }

    @Override
    public ResponseData<Boolean> assignResource(AdminRoleResourceAddParam roleResourceAddParam) {
        String userUuid = roleResourceAddParam.getUserUuid();
        String roleUuid = roleResourceAddParam.getRoleUuid();
        //删除旧关联
        SysRoleResourceDto paramDto = new SysRoleResourceDto();
        paramDto.setRoleUuid(roleUuid);
        sysRoleResourceMapper.del(paramDto);

        List<String> resources = roleResourceAddParam.getResources();
        List<SysRoleResourceDto> resourceDtoList = resources.stream().parallel().map(resourceUuid -> {
            SysRoleResourceDto sysRoleResourceDto = new SysRoleResourceDto();
            sysRoleResourceDto.setUuid(StringUtils.buildUUID());
            sysRoleResourceDto.setRoleUuid(roleUuid);
            sysRoleResourceDto.setResourceUuid(resourceUuid);
            sysRoleResourceDto.setCreateBy(userUuid);
            sysRoleResourceDto.setCreateOn(new Date());
            sysRoleResourceDto.setVersion(0);
            return sysRoleResourceDto;
        }).collect(Collectors.toList());

        return ResponseData.buildSuccessResponse("分配权限成功", sysRoleResourceMapper.addBatch(resourceDtoList) > 0);
    }
}